package net.mingsoft.report_data.biz.impl.report_gen;

import com.alibaba.fastjson.JSON;
import com.baomidou.dynamic.datasource.annotation.DS;
import net.mingsoft.report_data.biz.ZkDataSuspiciousBoatBiz;
import net.mingsoft.report_data.dao.ZkFzsDao;
import net.mingsoft.report_data.entity.vo.AreaDto;
import net.mingsoft.report_data.entity.vo.DigSuspiciousBoatRequestVO;
import net.mingsoft.report_data.entity.vo.IntelligenceDto;
import net.mingsoft.report_data.entity.vo.SuspiciousBoatDto;
import net.mingsoft.report_data.enums.ReportPeriodType;
import net.mingsoft.report_data.util.PeriodUtil;
import net.mingsoft.report_data.util.ReportFtlRender;
import org.slf4j.helpers.MessageFormatter;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service(value = "SMUGGLE_AND_DOCK")
@DS("fzs")
public class ZkDataSuspiciousBoatBizImpl implements ZkDataSuspiciousBoatBiz {

    @Resource
    ZkFzsDao fzsDao;

    @Resource
    FreeMarkerConfigurer configurer;

    private static final String DESC_HIDDEN_DOCK = "由上表可见，{}的{}累计活跃人数最多，共{}人";
    private static final String DESC_HIDDEN_DOCK_P2 = "，分布在{}的隐蔽码头最多，共{}个，其次是{}，共{}个，{}排第三，共{}个。";

    @Override
    public String generate(ReportPeriodType periodType) {
        Map<String, Object> map = PeriodUtil.getDateArgs(periodType);
        // 查询隐藏码头数据
        getHiddenDock(map);
        return ReportFtlRender.render(configurer, "report/form-zssa.ftl", map);
    }

    @Override
    public Map<String, Object> getHiddenDock(Map<String, Object> map) {
        List<SuspiciousBoatDto> suspiciousBoatDtoList = new ArrayList<>();

        final String beginDate = (String) map.get("beginDate");
        final String endDate = (String) map.get("endDate");
        // 统计不同区域（来自反走私区域管理）情报数
        List<IntelligenceDto> intelligenceDtoList = fzsDao.countIntelligence(beginDate, endDate);
        Map<String, IntelligenceDto> dtoMap = intelligenceDtoList.stream().collect(Collectors.toMap(IntelligenceDto::getPosName, o -> o, (a, b) -> a.setCount(a.getCount() + b.getCount())));

        // 获取区域名称：区域名称可能会被删除，所以需要从历史配置中取
        for (Map.Entry<String, IntelligenceDto> entry : dtoMap.entrySet()) {
            // 获取区域名字
            String ruleJsonStr = fzsDao.selectAreaNameFromHistoryConfigById(entry.getValue().getPosName());
            DigSuspiciousBoatRequestVO vo = JSON.parseObject(ruleJsonStr, DigSuspiciousBoatRequestVO.class);
            Map<String, AreaDto> areaDtoMap =
                    vo.getAreas().stream().collect(Collectors.toMap(AreaDto::getCode, o -> o));
            AreaDto areaDto = areaDtoMap.get(entry.getValue().getPosName());

            // 获取城市名称
            String cityName = fzsDao.selectCityFromCellInfoV2ByUli(entry.getValue().getUli());

            suspiciousBoatDtoList.add(new SuspiciousBoatDto()
                    .setCount(entry.getValue().getCount()).setCity(cityName).setAreaName(areaDto.getAreaName()));
        }

        // 排序
        suspiciousBoatDtoList.sort(Comparator.comparing(SuspiciousBoatDto::getCount));
        if (suspiciousBoatDtoList.size() > 0) {
            SuspiciousBoatDto dto0 = suspiciousBoatDtoList.get(0);
            SuspiciousBoatDto maxDto = suspiciousBoatDtoList.stream().max(Comparator.comparing(SuspiciousBoatDto::getCount)).get();
            String basicString = MessageFormatter.arrayFormat(DESC_HIDDEN_DOCK,
                    new String[]{maxDto.getCity(), maxDto.getAreaName(), String.valueOf(maxDto.getCount())}).getMessage();
            List<SuspiciousBoatDto> boatList
                    = suspiciousBoatDtoList.stream().collect(Collectors.groupingBy(SuspiciousBoatDto::getCity)).entrySet().stream().map(o -> new SuspiciousBoatDto().setCity(o.getKey()).setCount(o.getValue().size())).sorted(Comparator.comparing(SuspiciousBoatDto::getCount)).collect(Collectors.toList());
            if (boatList.size() >= 3) {
                SuspiciousBoatDto dto1= boatList.get(0);
                SuspiciousBoatDto dto2 = boatList.get(1);
                SuspiciousBoatDto dto3 = boatList.get(2);
                String appendString = MessageFormatter.arrayFormat(DESC_HIDDEN_DOCK_P2, new String[]{dto1.getCity(), String.valueOf(dto1.getCount()), dto2.getCity(), String.valueOf(dto2.getCount()), dto3.getCity(), String.valueOf(dto3.getCount())}).getMessage();
                map.put("suspiciousBoatDesc", basicString + "，" + appendString);
            } else {
                map.put("suspiciousBoatDesc", basicString);
            }
        }
        // 输出参数
        map.put("suspiciousBoatDtoList", JSON.toJSONString(suspiciousBoatDtoList));
        return map;
    }
}
